const router = require('koa-router')()
const connection = require('./mysql');
router.get('/', async (ctx, next) => {
  await ctx.render('index', {
    title: 'Hello Koa 2!'
  })
})

router.get('/string', async (ctx, next) => {
  ctx.body = 'koa2 string'
})

router.get('/json', async (ctx, next) => {
  ctx.body = {
    title: 'koa2 json'
  }
})
// 'select * from dizhi where isxianshi=1'
router.get('/dizhi', async (ctx, next) => {
  ctx.body = await connection.chazhao('SELECT * FROM dizhi ORDER BY morenis asc,time desc', []);
})
router.post('/adddizhi', async (ctx, next) => {
  console.log(ctx.request.body);
  var body = ctx.request.body
  // 先执行回调函数，不明白
  ctx.body = await ercengqiaotao('insert into dizhi(name,prov,city,district,dizhixiangqing,quma,phone,telephone,morenis,time) values(?,?,?,?,?,?,?,?,1,?)',[body[0].name, body[0].prov, body[0].city, body[0].district, body[0].dizhixiangqing, body[0].quma, body[0].phone, body[0].telephone, body[1]],connection.chazhao('update dizhi set morenis = \'0\'', []));
})
router.post('/xiugaidizhi', async (ctx, next) => {
  console.log(ctx.request.body);
  var body = ctx.request.body
    // 先执行回调函数，不明白
    ctx.body = await ercengqiaotao('update dizhi set name =?,prov =?,city =?,district =?,dizhixiangqing =?,quma =?,phone =?,telephone=?,morenis=1,time=? where id =?',[body[0].name, body[0].prov, body[0].city, body[0].district, body[0].dizhixiangqing, body[0].quma, body[0].phone, body[0].telephone, body[1],body[0].id],connection.chazhao('update dizhi set morenis = \'0\'', []))
})
router.post('/shezhimoren', async (ctx, next) => {
  console.log(ctx.request.body);
    // 先执行回调函数，不明白
    ctx.body = await ercengqiaotao('update dizhi set morenis = \'1\' where id =?',[ctx.request.body.id],connection.chazhao('update dizhi set morenis = \'0\'', []))
})
router.post('/dizhiashiyong', async (ctx, next) => {
  console.log(ctx.request.body);
    // 先执行回调函数，不明白
    ctx.body = await connection.chazhao('SELECT * FROM dizhi where id =?', [ctx.request.body.id])
})
router.post('/dizhishanchu', async (ctx, next) => {
  console.log(ctx.request.body);
  ctx.body = await connection.chazhao('update dizhi set isxianshi = \'0\' where id =?', [ctx.request.body.id]);
})
// 购物车

router.get('/gouwuche', async (ctx, next) => {
  // 多表查询去重
  var shangjia = await connection.chaxun('select DISTINCT(shangjia.id),shangjia.name from gouwuchegoods,shangjia  where gouwuchegoods.fuid=shangjia.id and gouwuchegoods.isshanchu=1',[]);
  for(var i=0;i<shangjia.length;i++){
    shangjia[i].isxuanzhong = false;
  }
  ctx.body = await tianjiacanshu(shangjia,'select * from gouwuchegoods where fuid=? and isshanchu=1');
})
router.post('/gouwucheshanchu', async (ctx, next) => {
  console.log(ctx.request.body);
  ctx.body = await connection.chazhao('update gouwuchegoods set isshanchu = \'0\' where id =?',[ctx.request.body.id]);
})
router.post('/addgouwuche', async (ctx, next) => {
  console.log(ctx.request.body);
  var body = ctx.request.body
  // 先执行回调函数，不明白
  ctx.body = await connection.chazhao('insert into gouwuchegoods(goodname,guige,danjia,shiliang,imgurl,fuid) values(?,?,?,?,?,?)', [body.goodname, body.guige, body.danjia, body.shiliang, body.imgurl, body.fuid]);
})
async function tianjiacanshu(e, sql) {
  var a = e;
  for (var i = 0; i < a.length; i++) {
    var _i = i;
    a[_i].nini = await new Promise((resolve, reject) => {
      connection.connection.query(sql, [a[_i].id], (error, results, fields) => {
        if (error) {
          resolve(error);
        } else {
          resolve(tianjiatrue(results,false));
        }
      });
    })
  }
  return a;
}
async function tianjiatrue(ee,s){
  var aa = ee;
  for(var i=0;i<aa.length;i++){
    aa[i].isxuanzhong = s;
  }
  return aa;
}

router.post('/suosuo', async (ctx, next) => {
  console.log(ctx.request.body);
  if(ctx.request.body.quanguois=="1"){
    if(ctx.request.body.ciridaois=="1"){
      switch(ctx.request.body.paixiu) {
        case 0:
          ctx.body = await connection.chazhao('select id,name,xiushici,tejia,danjia,imgurl from goods where name like ? and quanguois = 1 and ciridaois = 1 ORDER BY tejia asc;', ['%'+ctx.request.body.id+'%']);
           break;
        case 1:
          ctx.body = await connection.chazhao('select id,name,xiushici,tejia,danjia,imgurl from goods where name like ? and quanguois = 1 and ciridaois = 1 ORDER BY pingjia asc;', ['%'+ctx.request.body.id+'%']);
           break;
        default:
          ctx.body = await connection.chazhao('select id,name,xiushici,tejia,danjia,imgurl from goods where name like ? and quanguois = 1 and ciridaois = 1 ORDER BY id asc;', ['%'+ctx.request.body.id+'%']);
   } 
    }else{
      switch(ctx.request.body.paixiu) {
        case 0:
          ctx.body = await connection.chazhao('select id,name,xiushici,tejia,danjia,imgurl from goods where name like ? and quanguois = 1 ORDER BY tejia asc;', ['%'+ctx.request.body.id+'%']);
           break;
        case 1:
          ctx.body = await connection.chazhao('select id,name,xiushici,tejia,danjia,imgurl from goods where name like ? and quanguois = 1 ORDER BY pingjia asc;', ['%'+ctx.request.body.id+'%']);
           break;
        default:
          ctx.body = await connection.chazhao('select id,name,xiushici,tejia,danjia,imgurl from goods where name like ? and quanguois = 1 ORDER BY id asc;', ['%'+ctx.request.body.id+'%']);
    }
  }
}else{
  if(ctx.request.body.ciridaois=="1"){
    switch(ctx.request.body.paixiu) {
      case 0:
        ctx.body = await connection.chazhao('select id,name,xiushici,tejia,danjia,imgurl from goods where name like ? and ciridaois = 1 ORDER BY tejia asc;', ['%'+ctx.request.body.id+'%']);
         break;
      case 1:
        ctx.body = await connection.chazhao('select id,name,xiushici,tejia,danjia,imgurl from goods where name like ? and ciridaois = 1 ORDER BY pingjia asc;', ['%'+ctx.request.body.id+'%']);
         break;
      default:
        ctx.body = await connection.chazhao('select id,name,xiushici,tejia,danjia,imgurl from goods where name like ? and ciridaois = 1 ORDER BY id asc;', ['%'+ctx.request.body.id+'%']);
 } 
  }else{
    switch(ctx.request.body.paixiu) {
      case 0:
        ctx.body = await connection.chazhao('select id,name,xiushici,tejia,danjia,imgurl from goods where name like ? ORDER BY tejia asc;', ['%'+ctx.request.body.id+'%']);
         break;
      case 1:
        ctx.body = await connection.chazhao('select id,name,xiushici,tejia,danjia,imgurl from goods where name like ? ORDER BY pingjia asc;', ['%'+ctx.request.body.id+'%']);
         break;
      default:
        ctx.body = await connection.chazhao('select id,name,xiushici,tejia,danjia,imgurl from goods where name like ? ORDER BY id asc;', ['%'+ctx.request.body.id+'%']);
  }
}
}
})
router.post('/goodsid', async (ctx, next) => {
  console.log(ctx.request.body);
  ctx.body = await connection.chazhao('SELECT * FROM goods where id =?', [ctx.request.body.id]);
})
router.post('/shangjiaid', async (ctx, next) => {
  console.log(ctx.request.body);
  ctx.body = await connection.chazhao('SELECT * FROM shangjia where id =?', [ctx.request.body.id]);
})
router.post('/shangjiaidgoods', async (ctx, next) => {
  console.log(ctx.request.body);
  ctx.body = await connection.chazhao('SELECT * FROM goods where fuid =?', [ctx.request.body.id]);
})
router.post('/shishikan', async (ctx, next) => {
  console.log(ctx.request.body);
  const cha = new Promise((resolve, reject) => {
    connection.connection.query('select * from indexzong', (error, results, fields) => {
      var postData = { code: '10', data: results };
      if (error) {
        resolve(postData);
      } else {
        // const nicaia = indexzong(postData)
        postData.code = "100";
        resolve(indexzong(postData));
      }
    });
  });
  // console.log(cha);
  ctx.body = await cha;
})
async function indexzong(e) {
  var a = e;
  for (var i = 0; i < a.data.length; i++) {
    var _i = i;
    a.data[_i].ziji = await new Promise((resolve, reject) => {
      connection.connection.query('select * from indexzongfen where fuid=?', [a.data[_i].id], (error, results, fields) => {
        if (error) {
          resolve(error);
        } else {
          resolve(indexzongfen(results, 'select * from indexzongfenfen where fuid=?'));
        }
      });
    })
  }
  return a;
}

router.post('/indexshangjia', async (ctx, next) => {
  console.log(ctx.request.body);
  switch(ctx.request.body.paixiu) {
    case 0:
      ctx.body = await connection.chazhao('SELECT id,name,dizhi,pingfen,pingjun,url FROM shangjia ORDER BY pingjun asc;',);
       break;
    case 1:
      ctx.body = await connection.chazhao('SELECT id,name,dizhi,pingfen,pingjun,url FROM shangjia ORDER BY pingfen asc;',);
       break;
    default:
      ctx.body = await connection.chazhao('SELECT id,name,dizhi,pingfen,pingjun,url FROM shangjia ORDER BY id asc;',);
}
})
router.get('/libaiwu', async (ctx, next) => {
  ctx.body = await connection.chazhao('SELECT id,name,guige1,tejia,imgurl FROM goods where libaiwuis = 1', []);
})
router.get('/indexmian', async (ctx, next) => {
  const cha = new Promise((resolve, reject) => {
    connection.connection.query('select * from indexnav', (error, results, fields) => {
      var postData = { code: '10' };
      if (error) {
        resolve(postData);
      } else {
        // const nicaia = indexzong(postData)
        resolve(indexzongfen(results, 'select * from goods where guilie=? limit 4'));
      }
    });
  });
  ctx.body = await cha;
})
async function indexzongfen(e, sql) {
  var a = e;
  for (var i = 0; i < a.length; i++) {
    var _i = i;
    a[_i].nini = await new Promise((resolve, reject) => {
      connection.connection.query(sql, [a[_i].id], (error, results, fields) => {
        if (error) {
          resolve(error);
        } else {
          resolve(results);
        }
      });
    })
  }
  return a;
}
function ercengqiaotao(sql, a, fn) {
  return  new Promise((resolve, reject) => {
    connection.connection.query(sql, a, (error, results, fields) => {
      if (error) {
        resolve(error);
      } else {
        // 先执行回调fn函数，不能白原理
        resolve(fn);
      }
    });
  })

}
module.exports = router
